package top.lyc829.zzl_android.ui.thing.travel_detail;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.button.shinebutton.ShineButton;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xutil.data.DateUtils;
import com.youth.banner.adapter.BannerAdapter;
import com.youth.banner.indicator.RoundLinesIndicator;
import com.youth.banner.util.BannerUtils;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import okhttp3.Response;
import top.lyc829.zzl_android.MyApp;
import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.ActivityTravelDetailBinding;
import top.lyc829.zzl_android.logic.bean.BaseDetailBean;
import top.lyc829.zzl_android.logic.bean.DynamicBean;
import top.lyc829.zzl_android.logic.bean.ResultBean;
import top.lyc829.zzl_android.logic.bean.ShareBean;
import top.lyc829.zzl_android.logic.bean.SonCommentBean;
import top.lyc829.zzl_android.logic.bean.SubTravelBean;
import top.lyc829.zzl_android.logic.bean.SuperCommentBean;
import top.lyc829.zzl_android.logic.bean.TravelDetailBean;
import top.lyc829.zzl_android.logic.bean.TravelItemBean;
import top.lyc829.zzl_android.logic.network.Network;
import top.lyc829.zzl_android.logic.util.DynamicType;
import top.lyc829.zzl_android.logic.util.FellowType;
import top.lyc829.zzl_android.logic.util.HttpUtil;
import top.lyc829.zzl_android.logic.util.PageInfo;
import top.lyc829.zzl_android.logic.util.ReplayType;
import top.lyc829.zzl_android.logic.util.RichUtils;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.logic.util.gson.JsonUtilNew;
import top.lyc829.zzl_android.ui.base_detail.BaseDetailActivity;
import top.lyc829.zzl_android.ui.base_detail.CommentsAdapter;
import top.lyc829.zzl_android.ui.base_detail.SonCommentsAdapter;
import top.lyc829.zzl_android.ui.custom_view.InputTextMsgDialog;
import top.lyc829.zzl_android.ui.custom_view.ShareMsgDialog;
import top.lyc829.zzl_android.ui.index.ImageNetAdapter;
import top.lyc829.zzl_android.ui.login.LoginActivity;
import top.lyc829.zzl_android.ui.profile.follow.user_detail.OtherUserDetailActivity;
import top.lyc829.zzl_android.ui.thing.dynamic_detail.DynamicDetailActivity;

public class TravelDetailActivity extends AppCompatActivity {

    private ActivityTravelDetailBinding binding;
    private TravelDetailViewModel mViewModel;

    CommentsAdapter adapter;
    SonCommentsAdapter sonAdapter;
    PageInfo superCommentsPage,sonPageInfo;

    InputTextMsgDialog inputTextMsgDialog;
    MaterialDialog loadingDialog;
    BottomSheetDialog dialog;
    BottomSheetDialog deleteDialog;
    ShareMsgDialog shareMsgDialog;

    MiniLoadingDialog mMiniLoadingDialog;

    private int replayType = ReplayType.OTHER; // 回复类型，0 - 基地 1 - 评论
    private int commendedId = -1;    // 被评论的评论的id
    int commentedUserId = -1;

    boolean isNeedComment = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityTravelDetailBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        mViewModel = new ViewModelProvider(this).get(TravelDetailViewModel.class);
        mViewModel.getTravelIdLiveData().setValue(getIntent().getIntExtra("travel_id", -1));
        isNeedComment = getIntent().getBooleanExtra("is_comment", false);

        superCommentsPage = new PageInfo();
        sonPageInfo = new PageInfo();
        // 实例化加载框
        loadingDialog = new MaterialDialog.Builder(this)
                .customView(R.layout.dialog_loading_layout, true)
                .cancelable(false)
                .build();

        mMiniLoadingDialog =  WidgetUtils.getMiniLoadingDialog(this);
        mMiniLoadingDialog.updateMessage("加载中");
        mMiniLoadingDialog.setCancelable(false);

        initTitleBar();
        initBanner();
        initCommentAdapter();

        initCommentDialog();
        initLoadMore();

        observe();

        clickListener();

    }

    /**
     * 弹出底部删除弹窗
     */
    private void showBottomDialog() {
        if (deleteDialog == null) {
            deleteDialog = new BottomSheetDialog(this, R.style.MyBottomSheetDialog);
            View view = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_dialog_dynamic_long_click, null);

            view.findViewById(R.id.dynamic_long_delete).setOnClickListener(v -> {
                deleteComment();
                deleteDialog.dismiss();
            });

            view.findViewById(R.id.dynamic_long_cancel).setOnClickListener(v -> {
                deleteDialog.dismiss();
            });

            deleteDialog.setContentView(view);
            deleteDialog.setCancelable(true);
            deleteDialog.setCanceledOnTouchOutside(true);
        }
        deleteDialog.show();

    }

    /**
     * 删除评论
     */
    private void deleteComment() {
        if (mViewModel.getCommentDeleteLiveData().getValue() == null) {
            return;
        }
        Pair<Integer, Integer> commentPair = mViewModel.getCommentDeleteLiveData().getValue();

        int commentId;
        if (commentPair.first.equals(1)) {
            commentId = adapter.getItem(commentPair.second).getCommentId();
        } else {
            commentId = sonAdapter.getItem(commentPair.second).getCommentId();
        }
        Network.deleteComment(Utils.getUserId(), commentId, new HttpUtil.MyCallback() {
            @Override
            public void success(Response res) throws IOException {
                String resStr = res.body().string();
                ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                if (resultBean.getCode().equals(200)) {
                    runOnUiThread(() -> {
                        Utils.showToast("删除成功");
                        if (commentPair.first.equals(1)) {
                            adapter.removeAt(commentPair.second);
                            int num = Integer.parseInt(binding.travelDetailReplayNum.getText().toString());
                            binding.travelDetailReplayNum.setText(String.valueOf(num - 1));
                        } else {
                            sonAdapter.removeAt(commentPair.second);

                            if (mViewModel.getSonCommentChangePositionLiveData().getValue() != null) {
                                Pair<Integer, Integer> value = new Pair<>(mViewModel.getSonCommentChangePositionLiveData().getValue().first, -1);
                                mViewModel.getSonCommentChangePositionLiveData().postValue(value);
                            }
                        }
                    });
                } else {
                    failed(new IOException(resultBean.getMsg()));
                }
            }

            @Override
            public void failed(IOException e) {
                Utils.Sout(e.getMessage());
            }
        });
    }

    /**
     * 初始化底部评论弹窗
     */
    private void initCommentDialog() {
        if(inputTextMsgDialog == null) {
            inputTextMsgDialog = new InputTextMsgDialog(this, R.style.dialog_center);
            inputTextMsgDialog.setmOnTextSendListener(new InputTextMsgDialog.OnTextSendListener() {
                @Override
                public void onTextSend(String msg) {
                    inputTextMsgDialog.dismiss();

                    loadingDialog.show();


                    Network.sendComments(
                            Utils.getUserId(),
                            replayType,
                            commendedId,
                            msg,
                            commentedUserId,
                            new HttpUtil.MyCallback() {
                                @Override
                                public void success(Response res) throws IOException {
                                    String resultStr = res.body().string();
                                    ResultBean resultBean = new Gson().fromJson(resultStr, ResultBean.class);
                                    if (resultBean.getCode().equals(200)) {
                                        loadingDialog.dismiss();

                                        runOnUiThread(() -> {
                                            if (replayType == ReplayType.TRAVEL) {
                                                int num = Integer.parseInt(binding.travelDetailReplayNum.getText().toString()) + 1;
                                                binding.travelDetailReplayNum.setText(String.valueOf(num));
                                            }

                                            // 子评论界面没有加载，则刷新一级评论，否则刷新N级评论
                                            if (dialog == null || !dialog.isShowing()) {
                                                superCommentsPage.reset();
                                                // 重新获取以及评论
                                                mViewModel.loadSuperComments(ReplayType.TRAVEL, mViewModel.getTravelIdLiveData().getValue(), superCommentsPage.getPage());
                                            } else {
                                                sonPageInfo.reset();
                                                // 重新获取子评论
                                                mViewModel.loadSonComments(commendedId, sonPageInfo.getPage());

                                                if (mViewModel.getSonCommentChangePositionLiveData().getValue() != null) {
                                                    Pair<Integer, Integer> value = new Pair<>(mViewModel.getSonCommentChangePositionLiveData().getValue().first, 1);
                                                    mViewModel.getSonCommentChangePositionLiveData().postValue(value);
                                                }

                                            }
                                        });


                                    } else {
                                        failed(new IOException());
                                    }

                                }

                                @Override
                                public void failed(IOException e) {
                                    loadingDialog.dismiss();
                                    Utils.showToastSync("评论失败");
                                }
                            });


                }
            });
        }
    }


    /**
     * 在底部弹出评论的评论
     */
    private void showBottomSheetListDialog(SuperCommentBean superComment) {

        dialog = new BottomSheetDialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.replay_comments, null);
        RecyclerView recyclerView = view.findViewById(R.id.replay_recyclerview);

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.setLayoutManager(manager);
        sonAdapter = new SonCommentsAdapter();
        recyclerView.setAdapter(sonAdapter);
        sonAdapter.setList(null);

        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();

        ((TextView) view.findViewById(R.id.replay_nums)).setText("回复");
        // 点击箭头关闭BottomSheetDialog
        ((ImageButton) view.findViewById(R.id.replay_back_btn)).setOnClickListener(v -> dialog.cancel());

        ((TextView) view.findViewById(R.id.comment_item_username)).setText(superComment.getUserName());
        ((TextView) view.findViewById(R.id.comment_item_time)).setText(DateUtils.millis2String(Long.parseLong(superComment.getCommentTime()), DateUtils.yyyyMMdd.get()));
        ((TextView) view.findViewById(R.id.comment_item_text)).setText(superComment.getCommentText());
        ((TextView) view.findViewById(R.id.comment_item_go_replay)).setVisibility(View.GONE);
        //((TextView) view.findViewById(R.id.comment_item_like_nums)).setText(String.valueOf(superComment.getCommentLikes()));
        ((TextView) view.findViewById(R.id.comment_item_like_nums)).setVisibility(View.INVISIBLE);
        view.findViewById(R.id.comment_item_like_btn).setVisibility(View.INVISIBLE);
        Glide.with(this)
                .load(superComment.getImgUrl())
                .into((ImageView)view.findViewById(R.id.comment_item_avatar));

        // 点击子评论的评论框弹出评论框, 评论父评论
        view.findViewById(R.id.replay_bottom_comment).setOnClickListener(v -> {
            showCommentDialog();
            replayType = ReplayType.COMMENT;
            commendedId = superComment.getCommentId();
            commentedUserId = superComment.getUseId();
        });

        // 上拉加载
        initSonLoadMore(superComment.getCommentId());

        // 评论子评论
        sonAdapter.setOnItemClickListener((adapter1, view1, position) -> {
            showCommentDialog();
            replayType = ReplayType.COMMENT;
            commendedId = superComment.getCommentId();
            commentedUserId = sonAdapter.getData().get(position).getUseId();
        });

        sonAdapter.addChildClickViewIds(R.id.replay_item_like_btn,R.id.replay_item_avatar);
        sonAdapter.setOnItemChildClickListener((adapter1, view1, position) -> {
            if (view1.getId() == R.id.replay_item_like_btn) {
                // 子评论点赞
                if (!Utils.isLogin()) {
                    Utils.showToast("请先登录");
                    return;
                }


                View itemView = recyclerView.getLayoutManager().findViewByPosition(position);
                itemView.findViewById(R.id.replay_item_like_btn).setClickable(false);

                //ShineButton shineButton = (ShineButton) view;
                SonCommentBean sonComment = sonAdapter.getItem(position);
                //未点赞，点赞请求
                if (sonComment.getIsLike().equals(0)) {
                    Network.sendLike(Utils.getUserId(), ReplayType.COMMENT, sonAdapter.getItem(position).getCommentId(), new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resStr = res.body().string();
                            ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                            if (resultBean.getCode().equals(200)) {
                                runOnUiThread(() -> {
                                    View itemView = recyclerView.getLayoutManager().findViewByPosition(position);
                                    itemView.findViewById(R.id.replay_item_like_btn).setClickable(true);
                                    sonAdapter.getItem(position).setIsLike(1);
                                    sonAdapter.getItem(position).setCommentLikes(sonAdapter.getItem(position).getCommentLikes() + 1);
                                    sonAdapter.notifyDataSetChanged();
                                });
                            } else {
                                failed(new IOException(resStr));
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            runOnUiThread(() -> {
                                Utils.SoutErr(e.getMessage());
                                View itemView = recyclerView.getLayoutManager().findViewByPosition(position);
                                itemView.findViewById(R.id.replay_item_like_btn).setClickable(true);
                            });

                        }
                    });
                } else {
                    Network.sendUnLike(Utils.getUserId(), ReplayType.COMMENT, sonAdapter.getItem(position).getCommentId(), new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resStr = res.body().string();
                            ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                            if (resultBean.getCode().equals(200)) {
                                runOnUiThread(() -> {
                                    View itemView = recyclerView.getLayoutManager().findViewByPosition(position);
                                    itemView.findViewById(R.id.replay_item_like_btn).setClickable(true);
                                    sonAdapter.getItem(position).setIsLike(0);
                                    sonAdapter.getItem(position).setCommentLikes(sonAdapter.getItem(position).getCommentLikes() - 1);
                                    sonAdapter.notifyDataSetChanged();
                                });
                            } else {
                                failed(new IOException(resStr));
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            runOnUiThread(() -> {
                                Utils.SoutErr(e.getMessage());
                                View itemView = recyclerView.getLayoutManager().findViewByPosition(position);
                                itemView.findViewById(R.id.replay_item_like_btn).setClickable(true);
                            });
                        }
                    });
                }
            }  else if (view1.getId() == R.id.replay_item_avatar) {
                Intent intent = new Intent(TravelDetailActivity.this, OtherUserDetailActivity.class);
                intent.putExtra("id", sonAdapter.getItem(position).getUseId());
                startActivity(intent);
            }
        });


        // 子评论长按删除
        sonAdapter.setOnItemLongClickListener((adapter1, view1, position) -> {
            if (!Utils.isLogin()) {
                return false;
            }
            // 如果不是自己的评论，不做处理
            if (!sonAdapter.getItem(position).getUseId().equals(Utils.getUserId())) {
                return false;
            }

            mViewModel.getCommentDeleteLiveData().setValue(new Pair<>(2, position));
            showBottomDialog();

            return false;
        });

    }

    /**
     * 子评论上拉加载更多
     */
    private void initSonLoadMore(int superId) {
        sonAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                sonRequest(superId);
            }
        });
        sonAdapter.getLoadMoreModule().setAutoLoadMore(true);
        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        sonAdapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
    }

    /**
     * 弹出底部评论弹窗
     */
    private void showCommentDialog() {

        if (!Utils.isLogin()) {
            Utils.showToast("请先登录");
        } else {
            inputTextMsgDialog.show();
        }
    }


    /**
     * 评论适配器，使用基地详情页的adapter
     */
    private void initCommentAdapter() {
        adapter = new CommentsAdapter();
        adapter.setAnimationEnable(true);
        binding.travelCommentsRecycler.setLayoutManager(new LinearLayoutManager(this));
        binding.travelCommentsRecycler.setAdapter(adapter);
        adapter.setList(null);
    }


    private void initBanner() {
        binding.bannerTravelDetail.setDelayTime(5000);
        //banner.setAdapter(new ImageNetAdapter(bannerBeanList));
        binding.bannerTravelDetail.setAdapter(new BannerStringAdapter(null));
        binding.bannerTravelDetail.setIndicator(new RoundLinesIndicator(MyApp.getContext()));
        binding.bannerTravelDetail.setIndicatorSelectedWidth((int) BannerUtils.dp2px(15));
        binding.bannerTravelDetail.addBannerLifecycleObserver(this);
        binding.bannerTravelDetail.start();
    }

    private void initTitleBar() {
        binding.mTitleBarTravelDetail.setLeftClickListener(v -> finish());
        binding.mTitleBarTravelDetail.addAction(new TitleBar.ImageAction(R.drawable.ic_baseline_share_24) {
            @Override
            public void performAction(View view) {
                shareToDynamic();
            }
        });
    }

    private void clickListener() {
        binding.travelDetailFollow.setOnClickListener(v -> {
            if (!Utils.isLogin()) {
                Utils.showToast("请先登录");
                return;
            }

            if (mViewModel.getCollectionStateLiveData().getValue() != null
                    && mViewModel.getCollectionStateLiveData().getValue().equals(0)
                    && mViewModel.getTravelIdLiveData().getValue() != null
            ) {
                mMiniLoadingDialog.show();

                Network.collectionTravel(Utils.getUserId(), mViewModel.getTravelIdLiveData().getValue(), new HttpUtil.MyCallback() {
                    @Override
                    public void success(Response res) throws IOException {
                        String resultStr = res.body().string();
                        ResultBean<Void> resultBean = JsonUtilNew.fromJsonObject(resultStr, Void.class);
                        if (resultBean.getCode().equals(200)) {
                            // 重新获取关注关系
                            runOnUiThread(() -> {
                                mMiniLoadingDialog.dismiss();
                                mViewModel.getCollectionStateLiveData().setValue(1);
                            });
                        } else {
                            failed(new IOException(resultStr));
                        }
                    }

                    @Override
                    public void failed(IOException e) {
                        runOnUiThread(() -> {
                            mMiniLoadingDialog.dismiss();
                            Utils.showToastSync("收藏失败");
                        });


                    }
                });
            } else if (mViewModel.getCollectionStateLiveData().getValue() != null
                    && mViewModel.getCollectionStateLiveData().getValue().equals(1)
                    && mViewModel.getTravelIdLiveData().getValue() != null
            ) {
                Network.unCollectionTravel(Utils.getUserId(), mViewModel.getTravelIdLiveData().getValue(), new HttpUtil.MyCallback() {
                    @Override
                    public void success(Response res) throws IOException {
                        String resultStr = res.body().string();
                        ResultBean resultBean = new Gson().fromJson(resultStr, ResultBean.class);
                        if (resultBean.getCode().equals(200)) {
                            runOnUiThread(() -> {
                                mMiniLoadingDialog.dismiss();
                                mViewModel.getCollectionStateLiveData().setValue(0);
                            });
                        } else {
                            failed(new IOException(resultStr));
                        }
                    }

                    @Override
                    public void failed(IOException e) {
                        runOnUiThread(() -> {
                            mMiniLoadingDialog.dismiss();
                            Utils.showToastSync("取消收藏失败");
                        });
                    }
                });
            }


        });

        binding.travelBottomComment.setOnClickListener(v -> {
            showCommentDialog();
            replayType = ReplayType.TRAVEL;
            commendedId = mViewModel.getTravelIdLiveData().getValue();
        });

        adapter.addChildClickViewIds(R.id.comment_item_like_btn, R.id.comment_item_go_replay, R.id.comment_item_avatar);
        adapter.setOnItemClickListener((adapter, view, position) -> {
            showCommentDialog();
            replayType = ReplayType.COMMENT;    // 回复评论
            commendedId = ((SuperCommentBean) adapter.getData().get(position)).getCommentId();
            commentedUserId = ((SuperCommentBean) adapter.getData().get(position)).getUseId();
        });
        adapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter1, @NonNull View view, int position) {
                if (view.getId() == R.id.comment_item_go_replay) {

                    mViewModel.getSonCommentChangePositionLiveData().setValue(new Pair<>(position, Integer.MIN_VALUE));

                    sonPageInfo.reset();
                    // 弹出BottomSheetDialog, 显示评论评论的评论
                    showBottomSheetListDialog((SuperCommentBean) adapter.getData().get(position));
                    mViewModel.loadSonComments(((SuperCommentBean) adapter.getData().get(position)).getCommentId(), sonPageInfo.getPage());
                } else if (view.getId() == R.id.comment_item_like_btn) {
                    if (!Utils.isLogin()) {
                        Utils.showToast("请先登录");
                        return;
                    }

                    View itemView = binding.travelCommentsRecycler.getLayoutManager().findViewByPosition(position);
                    itemView.findViewById(R.id.comment_item_like_btn).setClickable(false);

                    //ShineButton shineButton = (ShineButton) view;
                    SuperCommentBean superComment = adapter.getItem(position);
                    //未点赞，点赞请求
                    if (superComment.getIsLike().equals(0)) {
                        Network.sendLike(Utils.getUserId(), ReplayType.COMMENT, adapter.getItem(position).getCommentId(), new HttpUtil.MyCallback() {
                            @Override
                            public void success(Response res) throws IOException {
                                String resStr = res.body().string();
                                ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                                if (resultBean.getCode().equals(200)) {
                                    runOnUiThread(() -> {
                                        View itemView = binding.travelCommentsRecycler.getLayoutManager().findViewByPosition(position);
                                        itemView.findViewById(R.id.comment_item_like_btn).setClickable(true);
                                        adapter.getItem(position).setIsLike(1);
                                        adapter.getItem(position).setCommentLikes(adapter.getItem(position).getCommentLikes() + 1);
                                        adapter.notifyDataSetChanged();
                                    });
                                } else {
                                    failed(new IOException(resStr));
                                }
                            }

                            @Override
                            public void failed(IOException e) {
                                runOnUiThread(() -> {
                                    Utils.SoutErr(e.getMessage());
                                    View itemView = binding.travelCommentsRecycler.getLayoutManager().findViewByPosition(position);
                                    itemView.findViewById(R.id.comment_item_like_btn).setClickable(true);
                                });

                            }
                        });
                    } else {
                        Network.sendUnLike(Utils.getUserId(), ReplayType.COMMENT, adapter.getItem(position).getCommentId(), new HttpUtil.MyCallback() {
                            @Override
                            public void success(Response res) throws IOException {
                                String resStr = res.body().string();
                                ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                                if (resultBean.getCode().equals(200)) {
                                    runOnUiThread(() -> {
                                        View itemView = binding.travelCommentsRecycler.getLayoutManager().findViewByPosition(position);
                                        itemView.findViewById(R.id.comment_item_like_btn).setClickable(true);
                                        adapter.getItem(position).setIsLike(0);
                                        adapter.getItem(position).setCommentLikes(adapter.getItem(position).getCommentLikes() - 1);
                                        adapter.notifyDataSetChanged();
                                    });
                                } else {
                                    failed(new IOException(resStr));
                                }
                            }

                            @Override
                            public void failed(IOException e) {
                                runOnUiThread(() -> {
                                    Utils.SoutErr(e.getMessage());
                                    View itemView = binding.travelCommentsRecycler.getLayoutManager().findViewByPosition(position);
                                    itemView.findViewById(R.id.comment_item_like_btn).setClickable(true);
                                });
                            }
                        });
                    }
                } else if (view.getId() == R.id.comment_item_avatar) {
                    Intent intent = new Intent(TravelDetailActivity.this, OtherUserDetailActivity.class);
                    intent.putExtra("id", adapter.getItem(position).getUseId());
                    startActivity(intent);
                }
            }
        });

        // 一级评论长按删除监听
        adapter.setOnItemLongClickListener((adapter1, view, position) -> {
            if (!Utils.isLogin()) {
                return false;
            }
            // 如果不是自己的评论，不做处理
            if (!adapter.getItem(position).getUseId().equals(Utils.getUserId())) {
                return false;
            }

            mViewModel.getCommentDeleteLiveData().setValue(new Pair<>(1, position));
            showBottomDialog();

            return false;
        });

        binding.travelDetailShare.setOnClickListener(v -> {
            shareToDynamic();
        });

        binding.travelDetailPraise.setOnClickListener(v -> {
            if (!Utils.isLogin()) {
                Utils.showToast("请先登录");
                return;
            }

            if (mViewModel.getIsPraiseLiveData().getValue() != null) {
                binding.travelDetailPraise.setClickable(false);
                int isLike = mViewModel.getIsPraiseLiveData().getValue();
                if (isLike == 0) {
                    Network.sendLike(Utils.getUserId(), ReplayType.TRAVEL, mViewModel.getTravelIdLiveData().getValue(), new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resStr = res.body().string();
                            ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                            if (resultBean.getCode().equals(200)) {
                                runOnUiThread(() -> {
                                    mViewModel.getIsPraiseLiveData().postValue(1);
                                    binding.travelDetailPraiseNum.setText(String.valueOf(Integer.parseInt(binding.travelDetailPraiseNum.getText().toString()) + 1));
                                    binding.travelDetailPraise.setClickable(true);
                                });

//                                TravelDetailBean travel = mViewModel.getTravelDetailLiveData().getValue();
//                                travel.setLikes(travel.getLikes() + 1);
//                                mViewModel.getTravelDetailLiveData().postValue(travel);
                            } else {
                                failed(new IOException(resultBean.getMsg()));
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            runOnUiThread(() -> {
                                Utils.SoutErr(e.getMessage());
                                binding.travelDetailPraise.setClickable(true);
                            });
                        }
                    });
                } else {
                    Network.sendUnLike(Utils.getUserId(), ReplayType.TRAVEL, mViewModel.getTravelIdLiveData().getValue(), new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resStr = res.body().string();
                            ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                            if (resultBean.getCode().equals(200)) {
                                runOnUiThread(() -> {
                                    mViewModel.getIsPraiseLiveData().postValue(0);
                                    binding.travelDetailPraiseNum.setText(String.valueOf(Integer.parseInt(binding.travelDetailPraiseNum.getText().toString()) - 1));
                                    binding.travelDetailPraise.setClickable(true);
                                });
//                                TravelDetailBean travel = mViewModel.getTravelDetailLiveData().getValue();
//                                travel.setLikes(travel.getLikes() - 1);
//                                mViewModel.getTravelDetailLiveData().postValue(travel);
                            } else {
                                failed(new IOException(resultBean.getMsg()));
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            runOnUiThread(() -> {
                                Utils.SoutErr(e.getMessage());
                                binding.travelDetailPraise.setClickable(true);
                            });
                        }
                    });
                }
            }
        });

        binding.travelDetailComment.setOnClickListener(v -> {
            showCommentDialog();
            replayType = ReplayType.TRAVEL;
            commendedId = mViewModel.getTravelIdLiveData().getValue();
        });

    }

    private void shareToDynamic() {
        if (!Utils.isLogin()) {
            Utils.showToast("请先登录");
            return;
        }
        if (shareMsgDialog == null) {
            TravelDetailBean travelDetail = mViewModel.getTravelDetailLiveData().getValue();

            StringBuilder stringBuilder = new StringBuilder();
            travelDetail.getContent().forEach(subTravelBean -> {
                stringBuilder.append(subTravelBean.getText());
            });

            shareMsgDialog = new ShareMsgDialog(
                    TravelDetailActivity.this,
                    R.style.dialog_center,
                    new ShareBean(travelDetail.getTitle(),
                            RichUtils.returnOnlyText(stringBuilder.toString()) ,
                            RichUtils.returnImageUrlsFromHtml(stringBuilder.toString()).get(0)));
            shareMsgDialog.setmOnTextSendListener(msg -> {
                shareMsgDialog.dismiss();
                loadingDialog.show();

                Network.shareToDynamic(DynamicType.TRAVEL, travelDetail.getId(), Utils.getUserId(),msg, new HttpUtil.MyCallback() {
                    @Override
                    public void success(Response res) throws IOException {
                        String resStr = res.body().string();
                        ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                        if (resultBean.getCode().equals(200)) {
                            runOnUiThread(() ->{
                                loadingDialog.dismiss();
                                Utils.showToast("分享成功");
                            });
                        } else {
                            failed(new IOException(resultBean.getMsg()));
                        }
                    }

                    @Override
                    public void failed(IOException e) {
                        runOnUiThread(() -> {
                            Utils.Sout(e.getMessage());
                            loadingDialog.dismiss();
                        });

                    }
                });

            });

        }

        shareMsgDialog.show();
    }


    private void observe() {
        mViewModel.getTravelIdLiveData().observe(this, integer -> {
            if (integer > 0) {
                // 游记id就是团队id
                mViewModel.getCollectionState(Utils.getUserId(), integer);
                mViewModel.loadTravelDetail(integer);
                mViewModel.getPraiseRelationShip(Utils.getUserId(), ReplayType.TRAVEL, integer);
                mViewModel.loadSuperComments(ReplayType.TRAVEL, integer, superCommentsPage.getPage());
            }
        });

        mViewModel.getCollectionStateLiveData().observe(this, integer -> {
            if (integer.equals(1)) {
                binding.travelDetailFollow.setText("已收藏");
                binding.travelDetailFollow.setBackgroundResource(R.drawable.btn_attentioned);
            }else {
                binding.travelDetailFollow.setText("收藏");
                binding.travelDetailFollow.setBackgroundResource(R.drawable.btn_un_attentioned);
            }
        });


        mViewModel.getTravelDetailLiveData().observe(this, travelDetailBean -> {
            binding.mTitleBarTravelDetail.setTitle(travelDetailBean.getTitle());

            StringBuilder stringBuilder = new StringBuilder();
            travelDetailBean.getContent().forEach(subTravelBean -> {
                stringBuilder.append(subTravelBean.getText());
            });

            if (RichUtils.returnImageUrlsFromHtml(stringBuilder.toString()).get(0).length() == 0) {
                binding.bannerTravelDetail.setVisibility(View.GONE);
            } else {
                binding.bannerTravelDetail.setVisibility(View.VISIBLE);
                binding.bannerTravelDetail.setDatas(RichUtils.returnImageUrlsFromHtml(stringBuilder.toString()));
            }


            binding.travelDetailTitle.setText(travelDetailBean.getTitle());

            initWebView(loadWebViewText(travelDetailBean.getContent()));

            binding.travelDetailReplayNum.setText(travelDetailBean.getComments() == null ? "0" : String.valueOf(travelDetailBean.getComments()));
            binding.travelDetailPraiseNum.setText(travelDetailBean.getComments() == null ? "0" : String.valueOf(travelDetailBean.getLikes()));

        });

        mViewModel.getSuperCommentsLiveData().observe(this, superCommentBeans -> {
            if (superCommentsPage.isFirstPage()) {
                adapter.setList(superCommentBeans);
                if (isNeedComment) {
                    binding.nestedScrollView.post(() -> {
                        binding.nestedScrollView.fullScroll(View.FOCUS_DOWN);//滚到底部
                    });
                }
            } else {
                adapter.addData(superCommentBeans);
            }

            if (superCommentBeans.size() < PageInfo.MAX_ITEM) {
                adapter.getLoadMoreModule().loadMoreEnd();
            } else {
                superCommentsPage.nextPage();
                // 加载完成，等待下一次加载
                adapter.getLoadMoreModule().loadMoreComplete();
            }
        });

        mViewModel.getIsPraiseLiveData().observe(this, integer -> {
            if (integer.equals(1)) {
                binding.travelDetailPraiseNum.setTextColor(Color.parseColor("#E54D42"));
                binding.travelDetailPraiseIcon.setImageResource(R.drawable.ic_baseline_thumb_up_red_20);
            } else {
                binding.travelDetailPraiseNum.setTextColor(Color.parseColor("#8A000000"));
                binding.travelDetailPraiseIcon.setImageResource(R.drawable.ic_baseline_thumb_up_gray_24);
            }
        });

        mViewModel.getSonCommentsLiveData().observe(this, sonCommentBeans -> {
            if (sonPageInfo.isFirstPage()) {
                sonAdapter.setList(sonCommentBeans);
            } else {
                sonAdapter.addData(sonCommentBeans);
            }
            if (sonCommentBeans.size() < PageInfo.MAX_ITEM) {
                sonAdapter.getLoadMoreModule().loadMoreEnd();
            } else {
                sonPageInfo.nextPage();
                // 加载完成，等待下一次加载
                sonAdapter.getLoadMoreModule().loadMoreComplete();
            }
        });

        // 一级评论被评论数量变化
        mViewModel.getSonCommentChangePositionLiveData().observe(this, integerIntegerPair -> {

            Utils.Sout( "pair---------" + integerIntegerPair.toString());

            if (integerIntegerPair == null || integerIntegerPair.first.equals(-1) || integerIntegerPair.second.equals(Integer.MIN_VALUE)) {
                return;
            }else {
                SuperCommentBean superComment = adapter.getItem(integerIntegerPair.first);
                superComment.setReplyNums(superComment.getReplyNums() + integerIntegerPair.second);
                adapter.setData(integerIntegerPair.first, superComment);
                adapter.notifyItemChanged(integerIntegerPair.first);
                mViewModel.getSonCommentChangePositionLiveData().setValue(new Pair<>(integerIntegerPair.first, Integer.MIN_VALUE));
            }

        });

    }

    /**
     * 上拉加载更多评论
     */
    private void initLoadMore() {
        adapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                request();
            }
        });
        adapter.getLoadMoreModule().setAutoLoadMore(true);
        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        adapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
    }

    private void request() {
        mViewModel.loadSuperComments(ReplayType.TRAVEL, mViewModel.getTravelIdLiveData().getValue(), superCommentsPage.getPage());
    }

    private void sonRequest(int superId) {
        mViewModel.loadSonComments(superId, sonPageInfo.getPage());
    }



    /**
     * 将html数组整合成html
     * @param content html数组
     * @return html字符串
     */
    private String loadWebViewText(List<SubTravelBean> content) {
        StringBuilder res = new StringBuilder();
        for (SubTravelBean itemBean : content) {
            if (itemBean.getText() != null) {
                res.append(itemBean.getText()).append("<br>");
            }
        }
        return res.toString();
    }

    public void initWebView(String data) {

        WebSettings settings = binding.travelDetailWebView.getSettings();

        //settings.setUseWideViewPort(true);//调整到适合webview的大小，不过尽量不要用，有些手机有问题
        settings.setAllowFileAccess(true);
        settings.setLoadWithOverviewMode(true);//设置WebView是否使用预览模式加载界面。
        settings.setAllowUniversalAccessFromFileURLs(true);
        settings.setAllowFileAccess(true);
        settings.setAllowFileAccessFromFileURLs(true);


        binding.travelDetailWebView.setVerticalScrollBarEnabled(false);//不能垂直滑动
        binding.travelDetailWebView.setHorizontalScrollBarEnabled(false);//不能水平滑动
        settings.setTextSize(WebSettings.TextSize.NORMAL);//通过设置WebSettings，改变HTML中文字的大小
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//支持通过JS打开新窗口
        //设置WebView属性，能够执行Javascript脚本
        binding.travelDetailWebView.getSettings().setJavaScriptEnabled(true);//设置js可用

        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//支持内容重新布局
        binding.travelDetailWebView.setWebViewClient(webViewClient);
        binding.travelDetailWebView.setWebChromeClient(new WebChromeClient());
        data = "</Div><head><style>body{font-size:16px}</style>" +
                "<style>img{ width:100% !important;margin-top:0.4em;margin-bottom:0.4em}</style>" +
                "<style>ul{ padding-left: 1em;margin-top:0em}</style>" +
                "<style>ol{ padding-left: 1.2em;margin-top:0em}</style>" +
                "</head>" + data;

        binding.travelDetailWebView.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);
    }

    public WebViewClient webViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }


        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }


        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            String url = request.getUrl().toString();
            return super.shouldOverrideUrlLoading(view, request);
        }


    };

    @Override
    protected void onDestroy() {

        if (shareMsgDialog != null && shareMsgDialog.isShowing()) {
            shareMsgDialog.dismiss();
        }
        shareMsgDialog = null;
        mMiniLoadingDialog.recycle();
        super.onDestroy();
    }
}